package com.embrion.utils;


import java.io.IOException;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Misc {

	
	public static void gotoPage(String addr, HttpServletRequest req, HttpServletResponse res, ServletContext context)
		throws ServletException, IOException{
		
		RequestDispatcher dispatcher = context.getRequestDispatcher(addr);		
		dispatcher.forward( req, res );
	}
	
	/**
	 * Svuota la sessione da tutti gli attributi.
	 * @param session
	 */
	public static void flushSession( HttpSession session ){
		
		@SuppressWarnings("unchecked")
		Enumeration<String> e = session.getAttributeNames();
		while( e.hasMoreElements() ){
			session.removeAttribute( (String)e.nextElement() );
		}
	}
	
	
	
	/**
	 * Converte un oggetto Date in una stringa nel formato "dd/MM/yyyy".
	 */
	public static String format( Date d )
	{
		String ret = "";
		if( d != null )
		{
			SimpleDateFormat sdf = new SimpleDateFormat( "dd/MM/yyyy" );
			ret = sdf.format( d );
		}
		return ret;
	}
	
	/**
	 * 
	 * Converte il formato di una Stringa dal formato "dd/MM/yyyy" a "yyyy-MM-dd"
	 */
	public static String cambiaFormato( String data )
	{
		String ret = "";
		if( (data != null) && (data.length() > 0) )
		{
			SimpleDateFormat sdf1 = new SimpleDateFormat( "dd/MM/yyyy" );
			SimpleDateFormat sdf2 = new SimpleDateFormat( "yyyy-MM-dd" );
			try {
				ret = sdf2.format( sdf1.parse( data ) );
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}
	
	public static Timestamp fromStringToTimestamp(String dataStringa) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = sdf.parse(dataStringa);
		Timestamp timestamp = new Timestamp(date.getTime());
		return timestamp;
	}
}